package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.converter.MachineConverters;
import org.dromara.system.domain.SimMallClassification;
import org.dromara.system.domain.SimMallName;
import org.dromara.system.domain.bo.SimMallClassificationBo;
import org.dromara.system.domain.vo.SimMallClassificationVo;
import org.dromara.system.domain.vo.SimMallNameVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SimMallClassificationMapper;
import org.dromara.system.service.ISimMallClassificationService;
import org.dromara.system.service.ISimMallNameService;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商城分类Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimMallClassificationServiceImpl extends ServiceImpl<SimMallClassificationMapper, SimMallClassification>
    implements ISimMallClassificationService {

    private final ISysUserService sysUserService;

    /**
     * 查询商城分类
     *
     * @param id 主键
     * @return 商城分类
     */
    @Override
    public SimMallClassificationVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询商城分类列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商城分类分页列表
     */
    @Override
    public TableDataInfo<SimMallClassificationVo> queryPageList(SimMallClassificationBo bo, PageQuery pageQuery) {
        IPage<SimMallClassificationVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimMallClassificationVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的商城分类列表
     *
     * @param bo 查询条件
     * @return 商城分类列表
     */
    @Override
    public List<SimMallClassificationVo> queryList(SimMallClassificationBo bo) {
        LambdaQueryWrapper<SimMallClassification> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimMallClassification> buildQueryWrapper(SimMallClassificationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SimMallClassification> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimMallClassification::getId);
        lqw.eq(bo.getUserId() != null, SimMallClassification::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getClassificationName()), SimMallClassification::getClassificationName, bo.getClassificationName());
        lqw.eq(bo.getSort() != null, SimMallClassification::getSort, bo.getSort());
        return lqw;
    }

    /**
     * 新增商城分类
     *
     * @param bo 商城分类
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimMallClassificationBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimMallClassification add = MapstructUtils.convert(bo, SimMallClassification.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商城分类
     *
     * @param bo 商城分类
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimMallClassificationBo bo) {
        SimMallClassification update = MapstructUtils.convert(bo, SimMallClassification.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimMallClassification entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商城分类信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<SimMallNameVo> queryMallClassification() {
        SysUserVo sysUserVo = sysUserService.selectUserById(LoginHelper.getUserId());
        ISimMallNameService simMallNameService = SpringUtil.getBean(ISimMallNameService.class);
        List<SimMallName> list = simMallNameService.lambdaQuery()
            .eq(SimMallName::getUserId, sysUserVo.getUserId())
            .list();
        if (CollUtil.isEmpty(list)) {
            return Lists.newArrayList();
        }
        List<Long> collect = list.stream().map(SimMallName::getId).collect(Collectors.toList());
        List<SimMallNameVo> brandVolist = MachineConverters.INSTANCE.toSimMallNameVoList(list);
        List<SimMallClassification> simMallClassifications = lambdaQuery().in(SimMallClassification::getMallNameId, collect).list();
        List<SimMallClassificationVo> ProductsLineVolist = MachineConverters.INSTANCE.toSimMallClassificationsVoList(simMallClassifications);
        brandVolist.forEach(t -> {
            List<SimMallClassificationVo> productsLineVos = ProductsLineVolist.stream().filter(t1 -> ObjectUtil.equal(t1.getMallNameId(), t.getId())).collect(Collectors.toList());
            t.setSimMallClassificationVoList(productsLineVos);
        });
        return brandVolist;
    }
}
